//
//  AutoSizeTextView.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/20.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit

class AutoSizeTextView: UITextView {
    
    let placeHolderLabel = UILabel()
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        self.font = UIFont.systemFont(ofSize: 15)
        
        placeHolderLabel.numberOfLines = 0
        placeHolderLabel.textColor = UIColor.darkGray
        self.addSubview(placeHolderLabel)
        
        self.rx.text.orEmpty
            .map { $0.count > 0 }
            .bind(to: placeHolderLabel.rx.isHidden)
            .disposed(by: rx.disposeBag)
    }
    
    var placeHolder: String? {
        set {
            placeHolderLabel.text = newValue
        }
        get {
            return placeHolderLabel.text
        }
    }
    
    var placeHolderColor: UIColor! {
        set {
            placeHolderLabel.textColor = newValue
        }
        get {
            return placeHolderLabel.textColor
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeHolderLabel.font = self.font
        
        let x = textContainerInset.left + textContainer.lineFragmentPadding
        let y = textContainerInset.top
        let width = bounds.size.width - textContainerInset.left - textContainerInset.right - textContainer.lineFragmentPadding * 2
        let height = bounds.size.height - textContainerInset.top - textContainerInset.bottom
        
        placeHolderLabel.frame = CGRect(x: 0, y: 0, width: width, height: height)
        placeHolderLabel.sizeToFit()
        placeHolderLabel.frame = CGRect(x: x, y: y, width: width, height: min(placeHolderLabel.frame.size.height, height))
        
        self.invalidateIntrinsicContentSize()
        if !(self.contentSize.height > self.bounds.size.height) {
            self.bounds.origin = .zero
        }
    }
    
    override var intrinsicContentSize: CGSize {
        return self.contentSize
    }
    
}
